from django.contrib import messages
from django.contrib.auth import get_user_model
from django.contrib.auth.hashers import make_password
from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin
from django.contrib.auth.models import Group, Permission
from django.contrib.messages.views import SuccessMessageMixin
from django.db.models import Q
from django.http import HttpResponseRedirect
from django.shortcuts import reverse, render
from django.views.generic import View, ListView, CreateView, UpdateView, DeleteView
from pure_pagination.mixins import PaginationMixin

from users.forms import ResetPasswordForm

User = get_user_model()


class IndexView(LoginRequiredMixin, View):
    """
    首页
    """

    def get(self, request):
        print(request.GET)
        return render(request, 'index.html')

    def post(self, request):
        print(request.POST)
        return render(request, 'index.html')

    def put(self, request):
        return render(request, 'index.html')


class UserListView(LoginRequiredMixin, PaginationMixin, ListView):
    """
    用户列表
    """
    model = User
    template_name = 'users/list.html'
    paginate_by = 5
    keyword = ''

    # 数据过滤
    def get_queryset(self):
        querset = super(UserListView, self).get_queryset()
        querset = querset.exclude(username='admin')
        self.keyword = self.request.GET.get("keyword", "")
        self.keyword = self.request.GET.get("keyword", "")
        if self.keyword:
            querset = querset.filter(Q(name__icontains=self.keyword) |
                                     Q(username__icontains=self.keyword) |
                                     Q(phone__icontains=self.keyword))
        return querset

    # 需要传给前端的数据大字典
    def get_context_data(self, **kwargs):
        context = super(UserListView, self).get_context_data(**kwargs)
        context['keyword'] = self.keyword
        return context


class UserAddView(LoginRequiredMixin, PermissionRequiredMixin, SuccessMessageMixin, CreateView):
    """
    用户添加
    """
    model = User
    template_name = 'users/form.html'
    fields = ('name', 'username', 'phone', 'sex',)
    success_message = "%(name)s was created successfully"
    permission_required = 'users.add_userprofile'

    def get_success_url(self):
        print(self.request.POST)
        if '_addanother' in self.request.POST:
            return reverse('users:add')
        return reverse('users:list')

    def form_valid(self, form):
        """
        用户默认密码为其用户名
        """
        print(form.cleaned_data)
        password = form.cleaned_data['username']
        print(make_password(password))
        print(form.instance)  # user = UserProfile.objects.get(pk=1)
        print(type(form.instance))
        form.instance.password = make_password(password)
        return super().form_valid(form)


class UserUpdateView(LoginRequiredMixin, PermissionRequiredMixin, SuccessMessageMixin, UpdateView):
    """
    用户更新
    """
    template_name = "users/form.html"
    model = User
    fields = ('username', 'name', 'phone', 'sex',)
    permission_required = 'users.change_userprofile'
    success_message = '%(name)s 更新成功！'

    def get_success_url(self):
        if '_addanother' in self.request.POST:
            return reverse('users:add')
        elif '_savedit' in self.request.POST:
            return reverse('users:modify', kwargs={'pk': self.kwargs['pk']})
        else:
            return reverse('users:list')


class UserDelateView(LoginRequiredMixin, PermissionRequiredMixin, DeleteView):
    """
    删除用户
    """
    template_name = 'users/user_confirm_delete.html'
    model = User
    permission_required = 'users.delete_userprofile'

    def get_success_url(self):
        return reverse('users:list')


class UserAddGroupView(LoginRequiredMixin, View):

    def get(self, request, pk):
        groups = Group.objects.all().values_list()
        user = User.objects.get(pk=pk)
        context = {'groups': groups, 'user': user}
        list_dd = list()
        for item in groups:
            dct = dict()
            ll = list(item)
            dct["id"] = ll[0]
            dct["value"] = ll[1]
            list_dd.append(dct)
        context["groups"] = list_dd

        return render(request, 'users/user_add_group.html', context=context)

    def post(self, request, pk):
        user = User.objects.get(pk=pk)
        groups = request.POST.getlist('groups')
        if user:
            user.groups.set(groups)
            set_group = user.groups.all().values()
            set_group = [item['name'] for item in set_group]
        else:
            user.groups.clear()
        messages.success(request, '用户添加或移除{}组成功！'.format(set_group))
        if '_addanother' in request.POST:
            return HttpResponseRedirect(reverse('users:addgroup', kwargs={'pk': pk}))
        return HttpResponseRedirect(reverse('users:list'))


class UserGroupView(LoginRequiredMixin, PermissionRequiredMixin, SuccessMessageMixin, UpdateView):
    """
    更新用户组信息（加入组，退出组）
    """
    template_name = 'users/user_newgrp.html'
    model = User
    fields = ('groups',)
    success_message = '加入或退出组成功！'
    permission_required = 'users.change_user'
    context_object_name = 'username'

    def get_success_url(self):
        if '_addanother' in self.request.POST:
            return reverse('users:user-newgrp', kwargs={'pk': self.kwargs.get('pk')})
        return reverse('users:list')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        groups = Group.objects.all()
        context['groups'] = groups
        return context

    def form_valid(self, form):
        print(form.cleaned_data)
        #u.groups.set(form.cleaned_data['groups'])
        return super(UserGroupView, self).form_valid(form)

class UserPermissionUpdateView(LoginRequiredMixin, PermissionRequiredMixin, SuccessMessageMixin, UpdateView):
        """
        更新用户权限
        """
        template_name = 'users/user_permission_update.html'
        model = User
        fields = ('user_permissions',)
        success_message = '用户权限编辑成功！'
        permission_required = 'users.change_user'
        context_object_name = 'username'

        def get_success_url(self):
            if '_addanother' in self.request.POST:
                return reverse('users:user-perm-update', kwargs={'pk': self.kwargs.get('pk')})
            return reverse('users:list')

        def get_context_data(self, **kwargs):
            context = super().get_context_data()
            permissions = Permission.objects.exclude(Q(content_type__model='session') |
                                                     Q(content_type__model='contenttype') |
                                                     Q(content_type__model='logentry')
                                                     ).values('id', 'name',
                                                              'content_type__model', 'content_type__app_label',
                                                              'codename')
            context['permissions'] = permissions
            return context

        def form_valid(self, form):
            print(form.cleaned_data)
            return super(UserPermissionUpdateView, self).form_valid(form)


class ResetPasswordView(LoginRequiredMixin, PermissionRequiredMixin, SuccessMessageMixin, UpdateView):
    """
    管理员重置密码
    """
    template_name = 'users/reset_password.html'
    model = User
    form_class = ResetPasswordForm
    # fields = ('password',)
    permission_required = 'users.change_userprofile'
    success_message = '重置密码成功！'

    def get_success_url(self):
        return reverse('users:list')

    def form_valid(self, form):
        password = form.cleaned_data.get('password')
        print(password)
        # password = make_password(password)
        # user.password = password
        # user.save()
        self.object.set_password(password)
        self.object.save()
        return super(ResetPasswordView, self).form_valid(form)